#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_customPlot = new QCustomPlot(this);
    m_customPlot->resize(300, 300);

    //可变数组存放绘图的坐标的数据，分别存放x和y坐标的数据，101为数据长度

    x.resize(101);
    y.resize(101);
    //添加数据，这里演示y=x^3，为了正负对称，x从-10到+10
    for (int i = 0; i<101; i++)
    {
        x[i] = i/5 - 10;
        y[i] = qPow(x[i], 3);//x的y次方;
    }

    //向绘图区域QCustomPlot添加一条曲线
    m_customPlot->addGraph();

    //添加数据
    m_customPlot->graph(0)->setData(x, y);

    //设置坐标轴名称
    m_customPlot->xAxis->setLabel("x");
    m_customPlot->yAxis->setLabel("y");

    //设置坐标轴显示范围，否则只能看到默认范围
    m_customPlot->xAxis->setRange(-11, 11);
    m_customPlot->yAxis->setRange(-1100, 1100);

    this->startTimer(1000);
}

void MainWindow::timerEvent( QTimerEvent * ) {
    static int i = 1;
    i *= -1;
    //所有数据前移移位，首位被覆盖
    for (int i = 0; i < 100; i++) {
        y[i] = y[i+1];
    }
    //最后一位为新数据（这里为随机数模拟）
    y[100] = qrand()%1000*i;
    //重新加载数据
    m_customPlot->graph(0)->clearData();
    m_customPlot->graph(0)->setData(x, y);
    m_customPlot->replot();
}

MainWindow::~MainWindow()
{
    delete ui;
}
